package concurrency.chapter6;

import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

/**
 * @author honway.liu
 * @date 2019-06-06 21:31
 * @email gm100861@gmail.com
 * @blog http://linuxsogood.org
 */
public class DiffWithSleepAndWait {

    static final byte[] lock = new byte[0];

    public static void main(String[] args) {
        Stream.of("T1", "T2").forEach(name -> {
            new Thread(DiffWithSleepAndWait::m2, name).start();
        });
    }

    /**
     * 使用sleep, 不会自动释放锁资源, 而且不能被唤醒
     */
    public static void m1() {
        synchronized (lock) {
            try {
                System.out.println(Thread.currentThread().getName() + " is enter.");
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 使用wait 可以释放锁资源, 需要被唤醒
     */
    public static void m2() {
        synchronized (lock) {
            try {
                System.out.println(Thread.currentThread().getName() + " is enter.");
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
